package offline;

import java.io.File;
import java.util.Random;

import tlsb.DBException;
import tlsb.Utils;
import util.IFileReader;
import util.IPartition;
import util.RedisCluster;
import util.RedisClusterFactory;

public class FlwshipLoader {
	final private String SETOFFOLLOWEES = ":fle";
	final private String SETOFFOLLOWERS = ":flr";
	final private String SETOFV = "vset";
	private String fshipFile = null;
	private String vipFile = null;

	static Random random = new Random();

	public FlwshipLoader(String fshipFile, String vipFile) {
		this.fshipFile = fshipFile;
		this.vipFile = vipFile;
	}

	// TODO 导入到单一的节点：207或者208
	public void connect() {

	}

	public void init() throws DBException {
		connect();
	}

	public void loadFollowshipAndUid() {
		// follow himself
		RedisCluster redisCluster = RedisClusterFactory.instance
				.getFolRedisCluster();
		IPartition part = redisCluster.getPartition();
		IFileReader ifr = new IFileReader(new File(fshipFile));
		ifr.open();
		String line = "";
		int counter = 0;
		while ((line = ifr.readLine()) != null) {
			counter++;
			if (counter % 1000000 == 0)
				System.out.println(counter);
			String[] tmp = line.split("\t");

			redisCluster.getPipeline(part.shard(tmp[1])).sadd(
					Utils.joinStr(tmp[1], SETOFFOLLOWEES), tmp[0]);
			redisCluster.getPipeline(part.shard(tmp[1])).sadd(
					Utils.joinStr(tmp[1], SETOFFOLLOWEES), tmp[1]);
			redisCluster.getPipeline(part.shard(tmp[0])).sadd(
					Utils.joinStr(tmp[0], SETOFFOLLOWERS), tmp[1]);
			redisCluster.getPipeline(part.shard(tmp[0])).sadd(
					Utils.joinStr(tmp[0], SETOFFOLLOWERS), tmp[0]);
			if (counter % 100 == 0)
				redisCluster.synAllPipelines();
		}
		redisCluster.synAllPipelines();
		System.out.println("followship counter:" + counter);
		// System.out.println("B counter:"+jedis.scard(ALLUIDS));
		ifr.close();
		redisCluster.close();
	}

	// 加载dav的频率
	public void loadV() {
		// follow himself
		RedisCluster redisCluster = RedisClusterFactory.instance
				.getMetaDataRedisCluster();
		IPartition part = redisCluster.getPartition();
		IFileReader ifr = new IFileReader(new File(vipFile));
		ifr.open();
		String line = "";
		int counter = 0;
		redisCluster.getJedis(0).del(SETOFV);
		while ((line = ifr.readLine()) != null) {
			counter++;
			redisCluster.getJedis(part.shard(SETOFV)).sadd(SETOFV,
					line.split("\t")[0]);
		}
		System.out.println("vip counter:" + counter + "_"
				+ redisCluster.getJedis(part.shard(SETOFV)).scard(SETOFV));

		ifr.close();
		redisCluster.close();
	}

	public void cleanup() throws DBException {
	}

	/**
	 * @param args
	 * @throws DBException
	 */
	public static void main(String[] args) throws DBException {
		// TODO Auto-generated method stub
		if (args.length != 2) {
			System.out.println("please provide followship and vip file");
			return;
		}
		FlwshipLoader loader = new FlwshipLoader(args[0], args[1]);
		loader.init();
		loader.loadFollowshipAndUid();
		loader.loadV();
		loader.cleanup();
	}
}
